from . import models
from rest_framework.serializers import ModelSerializer
from user.models import User
from rest_framework import serializers
from product.models import Product
import time
from django.core.cache import cache
from libs.iPay import alipay,settings,alipay_gateway

class AliPaySerializers(ModelSerializer):
    # go_time = serializers.DateTimeField(format='%Y-%m-%d')
    product_pk = serializers.CharField(max_length=16)
    class Meta:
        model = models.Order
        fields = [
            'subject',
            'total_amount',
            'pay_type',
            'product_pk',
            'peoples',
            'go_time',
            'pay_type',
        ]

        extra_kwargs = {
            'total_amount': {
                'required': True
            }
        }

    def validate(self, attrs):
        product_pk = attrs.get('product_pk')
        total_amount = attrs.get('total_amount')
        subject = attrs.get('subject')
        peoples = attrs.get('peoples')
        product_obj = Product.objects.filter(pk=product_pk,is_delete=False,is_show=True).first()
        if not product_obj:
            raise serializers.ValidationError({'pk':'产品主键有误'})
        if product_obj.price * int(peoples) != int(total_amount):
            raise serializers.ValidationError({'price': '价格有误'})
        order_on = self._get_order_no() #时间搓订单号

        order_params = alipay.api_alipay_trade_page_pay(out_trade_no=order_on,
                                                        total_amount=float(total_amount),
                                                        subject=subject,
                                                        return_url=settings.RETURN_URL,  # 同步回调的前台接口
                                                        notify_url=settings.NOTIFY_URL  # 异步回调的后台接口
                                                        )

        pay_url = alipay_gateway + order_params
        self.pay_url = pay_url
        cache.set(order_on,pay_url,7200)
        attrs['out_trade_no'] = order_on
        request = self.context.get('request')
        attrs['user'] = request.user
        attrs['product'] = product_obj
        attrs.pop('product_pk')
        return attrs


    def _get_order_no(self):
        no = '%s' % time.time()
        return no.replace('.', '', 1)


# class OrderModelSerializer(ModelSerializer):
#     class Meta:
#         model = models.Order
#         fields = [
#             'out_trade_no',
#             'status',
#             'subject',
#             'pay_time',
#             'peoples',
#             'product_cover',
#             'go_time',
#         ]

class DetailModelSerializer(ModelSerializer):
    class Meta:
        model = User
        fields  =[
            'orders',
        ]